package com.wmapp.connect;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wmapp.ConnectionException;
import com.wmapp.utils.SimpleStringUtils;

/**
 * Socket connect template class
 * @author dengl
 *
 */
public abstract class SocketSupport {
	private static Log log=LogFactory.getLog(SocketSupport.class);
	private ConnectConfig connectConfig=new ConnectConfig();
	
	public String execute(String request,Map params,String parameterRoot,boolean isWrapper){
		Request req=new Request(request, params,parameterRoot,isWrapper);
		return execute(req);
	}
	
	public String execute(String request,String xmlParam){
		Request req=new Request(request, xmlParam);
		return execute(req);
	}
	
	public String execute(String request,Map params,String parameterRoot){
		return execute(request,params,parameterRoot,false);
	}
	
	public String execute(String request,Map params){
		return execute(request,params,null,false);
	}
	
	public String execute(String request){
		return execute(request,null,null,false);
	}
	
	public String execute(Request req){
		String ret=null;
		Connection conn=null;
		try {
			conn=new Connection(connectConfig.getIp(), connectConfig.getPort());
			conn.sendXML(req.getContent());
			
			ret=conn.receiveXML();
		}catch (Exception e) {
			log.error(SimpleStringUtils.join("execute request ",req.getName()," fail."), e);
			throw new ConnectionException(e.getMessage());
		} finally{
			if(conn!=null)
				conn.close();
		}
		
		return ret;
	}

	public void setConnectConfig(ConnectConfig connectConfig) {
		this.connectConfig = connectConfig;
	}
}
